package cc.wanforme.st.server.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import cc.wanforme.st.server.base.constant.UserType;

/**
 * @author wanne
 *
 */
public class JwtUtil {
	private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);
	
	/** type+name+password 唯一, 同 type 下, name+password唯一
	 * @param type
	 * @param id
	 * @param name
	 * @expireHour 有效时间，小时
	 * @return
	 */
	public static String createToken(UserType type, String claimId, String username, int expireHour) {
		JWTCreator.Builder builder = JWT.create();
		builder.withClaim("type", type.name())
			.withClaim("claimId", claimId)
			.withClaim("timestamp", System.currentTimeMillis());
		
		LocalDateTime ex = LocalDateTime.now().plusHours(expireHour);
		builder.withExpiresAt(Date.from(ex.atZone(ZoneId.systemDefault()).toInstant()));
		return builder.sign(Algorithm.HMAC256(username));
	}
	
	
	/** 认证，可能没用
	 * @param token
	 * @param username
	 * @return
	 */
	public static DecodedJWT verify(String token, String username) {
		JWTVerifier builder = JWT.require(Algorithm.HMAC256(username)).build();
		return builder.verify(token);
	}
	
	/** 从token中获取类型
	 * @param token
	 * @param username
	 * @return
	 */
	public static String getType(String token) {
		try {
			return JWT.decode(token).getClaim("type").asString();
		} catch (Exception e) {
			log.error("获取类型失败", e);
			return null;
		}
	}
	
	/** 从token中获取ID
	 * @param token
	 * @param username
	 * @return
	 */
	public static Long getId(String token) {
		try {
			return JWT.decode(token).getClaim("claimId").asLong();
		} catch (Exception e) {
			log.error("获取ID失败", e);
			return null;
		}
	}
}
